package gc3d.servlet;

import gc3d.database.DBSettings;
import gc3d.database.GridPovDB;
import gc3d.ftp.FTPSettings;
import gc3d.ftp.GridPovFTP;
import gc3d.griddata.GridData;
import gc3d.griddata.GridPovData;
import gc3d.gridspring.GridPovRun;

import java.io.IOException;
import java.io.PrintWriter;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class GC3DServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/** doGet Method implementation */
	public void doGet(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<body>");
		out.println("<head>");
		out.println("<title>GC3D</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Give me file</h1>");
		out.println("<h2>We need you</h2>");
		out.println("<h3>..r file to render amazing stuff !</h3>");
		out.println("</body>");
		out.println("</html>");
		out.close();
	}

	/** Example of doPost Method implementation */
	public void doPost(HttpServletRequest req, HttpServletResponse res) {
		String taskID = "err";
		String error  = "error";
		//res.setContentType("text/plain");
		res.setContentType("text/html");

		PrintWriter out = null;
		try {
			out = res.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		out.print("<html><div id=\"JSON\">");

		try {
			// get the data from the form
			ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
			if(ServletFileUpload.isMultipartContent(req)){
				boolean aa = false;
				int width = 256, height = 160, aad = 2, 
					numberofframe = 5, x264bitrate = 800, fps = 5;
				double aat = 0.2, clock_start = 0, clock_end = 1;
				FileItem povFile = null;

				List<FileItem> fileItemList;
				fileItemList = servletFileUpload.parseRequest(req);

				Iterator<FileItem> it = fileItemList.iterator();
				while ( it.hasNext() ) {
					FileItem item = it.next();
					if ( item.isFormField() ) {
						if(item.getFieldName().equals("aa") ){
							aa = (item.getString() == null ? false : true);
						} else if(item.getFieldName().equals("width") ){
							width = Integer.parseInt(item.getString());
						} else if(item.getFieldName().equals("height")){
							height = Integer.parseInt(item.getString());
						} else if(item.getFieldName().equals("aat")){
							aat = Double.parseDouble(item.getString());
						} else if(item.getFieldName().equals("aad")){
							aad = Integer.parseInt(item.getString());
						} else if(item.getFieldName().equals("numberofframe")){
							numberofframe = Integer.parseInt(item.getString());
						} else if(item.getFieldName().equals("clock_start")){
							clock_start = Double.parseDouble(item.getString());
						} else if(item.getFieldName().equals("clock_end")){
							clock_end = Double.parseDouble(item.getString());
						} else if(item.getFieldName().equals("x264bitrate")){
							x264bitrate = Integer.parseInt(item.getString());
						} else if(item.getFieldName().equals("fps")){
							fps = Integer.parseInt(item.getString());
						}
					} else {
						povFile = item;
					}
				}
				if (povFile == null || povFile.getSize() == 0) {
					error = "Need POV-Ray file !";
				} else {
					// use String moreopts if user want specify own options
					GridPovData gpd   = new GridPovData(width, height, 
							numberofframe, clock_start, clock_end, aa, aat, 
							aad, povFile.getName(), povFile.get());
					GridPovFTP  gpftp = new GridPovFTP(FTPSettings.getFTPhost(), FTPSettings.getFTPport(), FTPSettings.getFTPuser(), FTPSettings.getFTPpass());
					GridPovDB   gpdb  = new GridPovDB(DBSettings.getDBURL(),DBSettings.getDBuser(),DBSettings.getDBpass());
					GridData    gd    = new GridData(gpd, gpftp, gpdb, povFile.get());
					GridPovRun  gpr   = new GridPovRun(gd, fps, x264bitrate);
	
					taskID = gd.getTaskID();
					error  = "no";
	
					// Thread for the Grid Rendering
					gpr.start();
				}
			} else {
				error = "Need multipart data !";
			}
		} catch (FileUploadException e) {
			error = "FileUploadException: "+e.getMessage();
		} catch (SQLException e) {
			error = "SQLException: "+e.getMessage();
		} catch (ClassNotFoundException e) {
			error = "HSQLDB ClassNotFoundException: "+e.getMessage();
		} catch (IOException e) {
			error = "IOException: "+e.getMessage();
		} finally {
			// JSON
			out.print("[{\"error\":\""+error+"\",\"taskID\":\""+taskID+"\",\"time\":"+Calendar.getInstance().getTimeInMillis()+"}]");
			out.print("</div></html>");
		}
	}

	/**
	 * overload info
	 */
	public String getServletInfo() {
		return "GC3D Servlet !";
	}
}
